package cn.tjad.tjad2.module.document.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import java.io.Serializable;
import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.Department;
import cn.tjad.tjad2.data.bean.Member;
import cn.tjad.tjad2.data.bean.PermissionBean;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

public class PermissionUpdateFragment extends BaseFragment implements IDataCallBack {
    @BindView(R.id.permission_name)
    TextView nameTV;
    @BindView(R.id.permission_view)
    CheckBox viewCB;
    @BindView(R.id.permission_create)
    CheckBox createCB;
    @BindView(R.id.permission_download)
    CheckBox downloadCB;
    @BindView(R.id.permission_move)
    CheckBox moveCB;
    @BindView(R.id.permission_rename)
    CheckBox renameCB;
    @BindView(R.id.permission_set_permission)
    CheckBox setPermissionCB;

    private PermissionBean permissionBean;
    private int permissionType = 0; //0:新增权限, 1:修改权限
    private int projectId;
    private int fileId;

    private String selectedType = null;
    private int selectedId = -1;

    @Override
    public View getContentView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.permission_update_layout, null);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        projectId = TjadApplication.getInstance().getSession().getProjectId();
        Bundle args = getArguments();
        if (args != null) {
            permissionBean = (PermissionBean) args.getSerializable(Keys.PERMISSION);
            permissionType = args.getInt(Keys.PERMISSION_TYPE, 0);
            fileId = args.getInt(Keys.FILE, -1);
            if (fileId == -1
                    || (permissionBean == null && permissionType == 1)) {
                Tools.showToast("修改权限:没有传入有效的参数");
                getActivity().finish();
            }
        }
        fillData(permissionBean);
    }

    private void fillData(PermissionBean data) {
        if (data == null) {
            nameTV.setText("点击选择权限主体");
            return;
        }
        if (data.company != null) {
            nameTV.setText(data.company.name);
        } else if (data.department != null) {
            nameTV.setText(data.department.name);
        } else if (data.user != null) {
            nameTV.setText(data.user.name);
        } else {
            nameTV.setText("");
        }
        nameTV.setEnabled(false);
        viewCB.setChecked(data.view);
        createCB.setChecked(data.create);
        downloadCB.setChecked(data.download);
        moveCB.setChecked(data.move);
        renameCB.setChecked(data.rename);
        setPermissionCB.setChecked(data.setPermission);
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        Bundle args = getArguments();
        if (args != null) {
            permissionType = args.getInt(Keys.PERMISSION_TYPE, 0);
        }
        if (permissionType == 0) {
            titleView.setCenterText("新增权限");
        } else {
            titleView.setCenterText("修改权限");
        }
    }

    @OnClick({R.id.confirm})
    public void onConfirm(View v) {
        boolean view = viewCB.isChecked();
        boolean create = createCB.isChecked();
        boolean download = downloadCB.isChecked();
        boolean move = moveCB.isChecked();
        boolean rename = renameCB.isChecked();
        boolean setPermission = setPermissionCB.isChecked();
        if (permissionType == 0) {
            if (selectedId <= 0 || selectedType == null) {
                Tools.showToast("请选择一个单位、部门或者人员！");
                return;
            }
            RemoteDataService.addPermission(projectId, fileId, selectedType, selectedId,
                    view, create, download, move, rename, setPermission, this);
        } else {
            RemoteDataService.updatePermission(projectId, fileId, permissionBean.id,
                    view, create, download, move, rename, setPermission, this);
        }
    }

    @OnClick({R.id.permission_name})
    public void onClick(View view) {
        if (view == nameTV) {
            RouteUtils.toPageForResult(getActivity(), PageId.PERMISSION_BODY_SELECT, null, 1002);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1002 && resultCode == Activity.RESULT_OK) {
            Serializable s = data.getSerializableExtra(Keys.BODY);
            if (s == null) {
                Tools.showToast("选择权利主体失败");
                return;
            }
            if (s instanceof Member) {
                selectedType = "company";
            } else if (s instanceof Department) {
                selectedType = "department";
            } else if (s instanceof User) {
                selectedType = "user";
            }
            try {
                Field field = s.getClass().getField("id");
                field.setAccessible(true);
                selectedId = field.getInt(s);
                field = s.getClass().getField("name");
                field.setAccessible(true);
                String name = (String) field.get(s);
                nameTV.setText(name);
            } catch (Exception e) {
                Tools.showToast("程序异常!");
                return;
            }
        }
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (TextUtils.isEmpty(errorMsg)) {
            Tools.showToast(errorMsg);
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        if (httpId == HttpId.ADD_PERMISSION || httpId == HttpId.UPDATE_PERMISSION) {
            CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                builder.setTitle("提示")
                        .setMessage("操作成功!")
//                        .setCancelable(false)
                        .setPositiveButton("确定", new OnDialogClickListener() {
                            @Override
                            public boolean onClick(Dialog dialogInterface, int i) {
                                getActivity().finish();
                                return true;
                            }
                        })
                        .show(getChildFragmentManager());
            } else {
                Tools.showToast(bean.respMsg);
            }
        }
    }
}
